package cn.xuyun.cc.tcp;

import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

import cn.xuyun.cc.tcp.coder.Decoder;
import cn.xuyun.cc.tcp.coder.MyDecoder;
import cn.xuyun.cc.tcp.vo.CallBack;


public class TcpServer {

	public static ConcurrentLinkedQueue<CallBack> linkQueue = new ConcurrentLinkedQueue<CallBack>();
	
	private static Logger log = Logger.getLogger(TcpServer.class);
	
	public static SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public static void main(String[] args) throws Exception{
			

			
	// Configure the server.
			ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

			 // Set up the event pipeline factory.
	        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
	            public ChannelPipeline getPipeline() throws Exception {
	                return Channels.pipeline(new Decoder());
	            }
	        });
			
			// Bind and start to accept incoming connections.
			int port = 4000;
			if (args.length > 0) {
				port = Integer.parseInt(args[0]);
			}
			bootstrap.bind(new InetSocketAddress(port));
			//bootstrap.bind(new InetSocketAddress(4001));//控制台端口
			
			Timer timer=new Timer(true); // daemon thread task
			timer.schedule(new CallBackThread(), 1000, 5000);
			
			
		}
		
		public static class CallBackThread extends TimerTask
		{
			@Override
			public void run() {
				// TODO Auto-generated method stub
				HashMap<String, List<CallBack>> map=new HashMap<String, List<CallBack>>();
				while(!linkQueue.isEmpty())
				{
					CallBack cb=linkQueue.poll();
					if(map.containsKey(cb.getCmdkey()))
					{
						List<CallBack> list=map.get(cb.getCmdkey());
						list.add(cb);
					}else{
						List<CallBack> list=new ArrayList<CallBack>();
						list.add(cb);
						map.put(cb.getCmdkey(), list);
					}
				}
				//send callback
				DefaultHttpClient client=new DefaultHttpClient();
				for(List<CallBack> list:map.values())
				{
					if(list.size()>0)
					{
						log.info("send callback:"+list.size());
						StringBuilder sb=new StringBuilder();
						String timestamp=sdf.format(new Date());
						sb.append("{");
						sb.append("\"cmdkey\":\""+list.get(0).getCmdkey()+"\",");
						sb.append("\"timestamp\":\""+timestamp+"\",");
						sb.append("\"data\":[");
						for(CallBack cb:list)
						{
						sb.append("{");
						sb.append("\"uid\":\""+cb.getDeviceId()+"\",");
						sb.append("\"timestamp\":\""+cb.getTimestamp()+"\",");
						sb.append("\"content\":\""+new String(cb.getDeviceResponse())+"\"");
						sb.append("}");
						}
						sb.append("]");
						sb.append("}");
						
						HttpPost post = new HttpPost(list.get(0).getCallback());
						try {
							post.setEntity(new StringEntity(sb.toString(),"UTF-8"));
							client.execute(post);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
					
					
			}
		}
		
}
